package com.lll.serialization;

import com.alibaba.fastjson.JSON;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianSerializerInput;
import com.caucho.hessian.io.HessianSerializerOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public interface Serialization {

    <T> byte[] serialize(T message);

    <T> T deserialize(Class<T> clazz, byte[] bytes);

    enum Algorithm implements Serialization {
        Json {
            @Override
            public <T> byte[] serialize(T message) {
                return JSON.toJSONBytes(message);
            }

            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                return JSON.parseObject(bytes, clazz);
            }
        },
        hession {
            public <T> byte[] serialize(T obj) {
                if (null == obj) {
                    throw new NullPointerException();
                }
                byte[] res;
                try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                    Hessian2Output output = new HessianSerializerOutput(os);
                    output.writeObject(obj);
                    output.flush();
                    res = os.toByteArray();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return res;
            }

            @Override
            public <T> T deserialize(Class<T> clazz, byte[] data) {
                if (data.length == 0) {
                    return null;
                }
                T result;
                try (ByteArrayInputStream is = new ByteArrayInputStream(data)) {
                    Hessian2Input input = new HessianSerializerInput(is);
                    result = (T) input.readObject(clazz);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return result;
            }
        }
    }
}
